﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Amazon_Book_Search.AmazonService;

namespace Amazon_Book_Search.Models
{
    public class SearchPage
    {
        private const int amazonResultsPerPage = 10;
        private const int resultsPerPage = 13;

        private int pageNumber;   // start counting from 1
        public int PageNumber
        {
            get { return pageNumber; }
            set { pageNumber = value; }
        }

        private int numPages;
        public int NumPages
        {
            get { return numPages; }
            set { numPages = value; }
        }

        private int numResults;
        public int NumResults
        {
            get { return numResults; }
            set { numResults = value; }
        }

        private String query;
        public String Query
        {
            get { return query; }
            set { query = value; }
        }

        private List<AmazonItem> items;
        public List<AmazonItem> Items
        {
            get { return items; }
            set { items = value; }
        }

        public SearchPage(String title, int num)
        {
            query = title;
            pageNumber = num;
            generatePage(title, num);
        }

        public SearchPage()
        {
        }

        private void generatePage(String s, int pageNum)
        {
            int start = (pageNum - 1) * resultsPerPage;         // index of the first element
            int end = pageNum * resultsPerPage - 1;             // index of the last element
            int firstPageToGet = start / amazonResultsPerPage;  // 0-based
            int lastPageToGet = end / amazonResultsPerPage;

            List<AmazonItem> items = new List<AmazonItem>();
            int firstElem = start % 10;
            int lastElem = firstElem + resultsPerPage;

            ItemWrapper itmWrapper = null;
            int currentPage = firstPageToGet;
            for (int i = firstElem; i < lastElem; i++)
            {
                if (i == firstElem || i == 10) {
                    itmWrapper = ItemWrapper.getItemsFromAmazon(s, currentPage + 1);
                    currentPage++;
                }

                if (i % amazonResultsPerPage >= itmWrapper.Items.Count)
                {
                    break;
                }

                items.Add(itmWrapper.Items[i % amazonResultsPerPage]);
            }

            numResults = itmWrapper.ResultCount;
            numPages = (numResults + resultsPerPage - 1) / resultsPerPage;

            this.items = items;
        }

    }
}